package com.tros.customer.features;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tros.customer.notification.MailNotification;

/**
 * Servlet implementation class FixedDepInv
 */
@WebServlet("/FixedDepInv")
public class FixedDepInv extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FixedDepInv() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		Connection connect =null;			 
		HttpSession ses = request.getSession(); 
		
		String accType = request.getParameter("accType");
		String accNo = request.getParameter("accno");
		String balance = request.getParameter("balAmt");
		String invamt = request.getParameter("invamt");
		String fdOption = request.getParameter("fdOption");
	
		String[] parts = fdOption.split("/");
		String period = parts[0]; 
		String percent = parts[1];
		
		System.out.println("accType :"+accType);
		System.out.println("balance :"+balance);

		System.out.println("invamt :"+invamt);
		System.out.println("accNo :"+accNo);
		System.out.println("fdOption :"+fdOption);
		System.out.println("period :"+period);
		System.out.println("percent :"+percent);
		
		String[] per = period.split(" ");
		
		String Months = per[0];

		try{
	           if(Double.parseDouble(balance) < Double.parseDouble(invamt))
	           {
	        	   System.out.println("came here ------->balance less");
	        	   ses.setAttribute("fdShrResult", "Fixed Deposit Amount Exceeds Account Balance . Please Change Account or Invest in less Amount");
			       response.sendRedirect("invdePass.jsp");
			       
	           }else
	           {
	        	   System.out.println("came here ------->balance ok");
	        	   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			       connect =DriverManager.getConnection("jdbc:odbc:bank","root", " ");
		           System.out.println("DB Connection created :"+connect);
		           
	        	   Double bal = Double.parseDouble(balance)- Double.parseDouble(invamt);
		           System.out.println("----------> amount ---------->"+bal);
		           
		           
		        	   DetectAcc(connect,accType,accNo,bal,ses);
		        	   
		        	   ses.setAttribute("fdShrResult", "Fixed Deposit Investment is Successfully Done");
				       response.sendRedirect("invdePass.jsp");
				       
				       try{
							
							UpdateTrans trans = new UpdateTrans(connect,accNo,accType,"Fixed Deposit Investment",invamt,String.valueOf(ses.getAttribute("currentID")));
							trans.updateTransValues();
							 
							 						 
						}catch(Exception e)
						{
							e.printStackTrace();
							System.out.println(" -----------> Failed in updation trans --------");
						}
				       
				       try{
				    	   
				    	    Calendar cal= Calendar.getInstance(); 
				   	        cal.add(Calendar.MONTH, Integer.parseInt(per[0])); 
				   	    
				   	        Date date = cal.getTime(); 
				   	        
				   	        SimpleDateFormat form = new SimpleDateFormat("MM/dd/yyyy");
				   		    String day = form.format(date); 
				   		    
				   		     Double AmtInt = Double.parseDouble(invamt) * Math.pow((1 + Double.parseDouble(percent)/100),Integer.parseInt(per[0]));
							
                            updateFd(connect,String.valueOf(ses.getAttribute("currentID")),day,invamt,percent,AmtInt);						 
							 						 
						}catch(Exception e)
						{
							e.printStackTrace();
							System.out.println(" -----------> Failed in updation trans --------");
						}     
				         
						
						try{
							
							String email = "";
							String lname = "";
							
							PreparedStatement state=connect.prepareStatement("SELECT * FROM EXISTUSERS WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));
							ResultSet result=state.executeQuery();
							
							while(result.next()){
								
							      email=result.getString("EMAIL");
							      lname=result.getString("LASTNAME");
							}
							
							state.close();
							
							MailNotification mail = new MailNotification(email);
						    
						    String text = "Hello "+ lname + 
							    		      "\n\n Fixed Deposit Investment is been performed in your"+
							    		      "\n\n Account : "+accType+
							    		      "\n Number : "+accNo+
							    	      "\n FD Amount : "+invamt+
							    		       "\n Time Period : "+period+
							    		      "\n\n Note : Please do not reply to this E-Mail Notification";
							    
							mail.sendMail( "Fixed Deposit Investment", text);
							connect.close();
							
						}catch(Exception e){
							e.printStackTrace();
							System.out.println(" -----------> Failed in Mail notification --------");
						}
		         
	           }
	           
		}catch(Exception e)
		{
			ses.setAttribute("fdShrResult", "Fixed Deposit Failure \n Please Try again");
	        response.sendRedirect("invdePass.jsp");
			System.out.println("Failed here --------->"+e.getMessage());
	       	e.printStackTrace();
		}
	}



private void updateFd(Connection connect, String valueOf, String day,
			String invamt, String percent, Double amtInt) {
		// TODO Auto-generated method stub
	
	 try{			
            
		   System.out.println("Update Fd Account");
		 
		    PreparedStatement state1=connect.prepareStatement("INSERT INTO FIXEDDEPOSIT VALUES(?,?,?,?,?,?)");
		    
		    state1.setString(1,valueOf);
		    state1.setString(2,day);
		    state1.setString(3,invamt);
		    state1.setString(4,new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date()));
		    state1.setString(5,percent);
		    state1.setString(6,String.valueOf(amtInt));

		    state1.executeUpdate();	
		    state1.close();
			
		}catch(Exception e){
			System.out.println("update table--------->"+e.getMessage());
		}
		
	}

private void DetectAcc(Connection connect, String accType, String accNo,
		Double bal, HttpSession ses) {
	// TODO Auto-generated method stub
	
	try{
		PreparedStatement state;
		
		  if(accType.equals("Savings")){				  
			  state=connect.prepareStatement( "UPDATE SAVACC SET ACC_BALANCE=? WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));            
		  }else
		  {				  
			   state=connect.prepareStatement( "UPDATE CHCKACC SET ACC_BALANCE=? WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));	           
		  }
		  
		state.setString(1,String.valueOf(bal));
   	    state.executeUpdate();
   	    state.close();
  		System.out.println("---------> connect value ------"+connect);
		
	}catch(Exception e)
	{
		System.out.println("Failed here update amount --------->");
		e.printStackTrace();
	}
	
}
	
	
}
